//
//  State_IngameLayer2.m
//  FunnyRacing
//
//  Created by vy phan on 4/23/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "State_IngameLayer2.h"


@implementation State_IngameLayer2

static inline float clamp(float a, float min, float max) {
	if (a < min) return min;
	if (a > max) return max;
	
	return a;
}

- (id)init
{
	self = [super init];
	if (self != nil) {
		CGSize winsize = [[CCDirector sharedDirector]winSize];
		int screenW = winsize.width;
		int screenH = winsize.height;
		
		car = [[Car alloc]initCarWithType:WCAR];
		car.position = ccp(screenW / 2, screenH / 2);
		car.tag = 1;
		[self addChild:car z:1];
		
		map = [[Map alloc]initWithMapName:@"first"];
		map.position = ccp(car.position.x, car.position.y - 125);
		[self addChild:map z:0];
		
		dpad = [[DPad alloc]init];
		dpad.position = CGPointZero;
		[self addChild:dpad z:2];
		[self schedule:@selector(controlCar:) interval:1.0/60];
		
	}
	return self;
}
-(void)controlCar:(ccTime)dt{
	// khong bam chi het thi toc do se cham dan lai//
	//	if (dpad.direction == -1){
	//		if (car.speed > 0.5) {
	//			car.speed -= (float)car.speed*car.speedDecay;
	//		}
	//		else {
	//			car.speed = 0;
	//		}
	//	}
	switch (dpad.direction) {
		case DPAD_UP:
			if (car.speed < car.maxSpeed) {
				car.speed += car.accel;
			}
			break;
		case DPAD_DOWN:
			//if (car.speed > 0) {
			car.speed = -car.backSpeed;
			//}
			//else {
			//car.speed = 0;
			//}
			
			break;
		case DPAD_LEFT:
		{
			car.rotation -= car.rotationStep*((float)car.speed / car.maxSpeed);
			break;
		}
		case DPAD_RIGHT:
		{
			car.rotation += car.rotationStep*((float)car.speed / car.maxSpeed);
			break;
		}
		default:
			break;
	}
	//we calculate the two components of speed (X axis and Y axis) - we have already discussed this part of the function above
	// toa do tren iphone (0,0) nam o doc duoi ben trai nen phai la * -1
	float carX = -sin([car rotation]*(M_PI/180))*car.speed;
	float carY = -cos([car rotation]*(M_PI/180))*car.speed;
	
	printf("carX = %f\n", carX);
	printf("carY = %f\n", carY);
	// xét lại tọa độ sau mỗi lần tính toán	
	car.position = ccp(car.position.x + carX, car.position.y + carY);
	if (car.position.x < car.contentSize.width / 2) {
		car.rotation += 5;
	}

	float mapX = map.position.x - carX;
	float mapY = map.position.y - carY;
	if (mapX <= 480 - map.contentSize.width / 2 - 20) {
		mapX = 480 - map.contentSize.width / 2 - 20;
	}
	if (mapX >= map.contentSize.width / 2 + 20) {
		mapX = map.contentSize.width / 2 + 20;
		return;
	}
	if (mapY <= 320 - map.contentSize.height / 2 - 20) {
		mapY = 320 - map.contentSize.height / 2 - 20;
	}
	if (mapY >= map.contentSize.height / 2 + 20) {
		mapY = map.contentSize.height + 20;
	}
	map.position = ccp(mapX, mapY);
}

@end
